using UnityEngine;
using System.Collections;

public class MoveController : MonoBehaviour
{

	public float heightOverGround = 1.0f;
	public float upForce = 500.0f;
	public float forwardForce = 10.0f;

	private float timeSinceLastPress = 1;
	public float timeBetweenPresses = 0.5f;
	public float flapUpForce = 500.0f;
	private bool keyWasPressed = false;
	

	public float rotationSpeed = 5.0f;

	
	//private float rotationDelta = 20.0f;

	// Use this for initialization
	void Start()
	{


	}

	// Update is called once per frame
	void FixedUpdate()
	{
       /*float tempHeightOverGround = heightOverGround;
        float downForce = 0f;
        PickUpStuff pickup = GetComponentInChildren<PickUpStuff>();
        if (pickup.hasItem)
        {
            tempHeightOverGround += Mathf.Abs(pickup.joint.connectedBody.collider.bounds.size.y);
           // print(tempHeightOverGround);

        }*/
		

		Vector3 rayPos = this.transform.position;
		Vector3 rayDir = new Vector3(0, -1, 0);
		RaycastHit hitInfo;

		//Vector3 objectDir = transform.position - GameObject.Find("Main Camera").transform.position;
		//objectDir.Normalize();

        if (Physics.Raycast(rayPos, rayDir, out hitInfo, heightOverGround, 2))
		{
			rigidbody.AddForce(new Vector3(0, upForce * Time.deltaTime, 0));
            print("fly");
            
		}

		
		timeSinceLastPress += Time.deltaTime;
		if( !keyWasPressed && Input.GetKey( KeyCode.UpArrow ) &&  timeSinceLastPress > timeBetweenPresses )
		{
            transform.BroadcastMessage("Flap", timeBetweenPresses);
            // TAX: Send message to flap wings here!!!
			rigidbody.AddForce( - Physics.gravity * Time.deltaTime  * flapUpForce );
			timeSinceLastPress = 0;
			keyWasPressed = true;
		}
		if( !Input.GetKey( KeyCode.UpArrow ) )
			keyWasPressed = false;

		rigidbody.AddForce(-Vector3.right * forwardForce * Input.GetAxis("Horizontal"));

		float x = Input.GetAxis("Horizontal") != 0 ? -Input.GetAxis("Horizontal") : rigidbody.velocity.x;
		Vector3 v = new Vector3(x, 0, 0);
		if (v != Vector3.zero)
			transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(v), Time.deltaTime * rotationSpeed);
		
		this.transform.position = new Vector3( this.transform.position.x, this.transform.position.y, 0);
		
	}
}
